package com.cy.pj.sys.service.impl;

import com.cy.pj.common.annotation.RequiredLog;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.service.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

@Transactional(rollbackFor = Throwable.class,isolation = Isolation.READ_COMMITTED,timeout = 60)
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    @Transactional(readOnly = true)
    @RequiredLog("日志分页查询")
    @Override
    public List<SysUser> findUsers(SysUser sysUser) {
        return sysUserDao.selectUsers(sysUser);
    }

    @Transactional(readOnly = true)
    @Override
    public SysUser findById(Integer id)  {
        SysUser sysUser = sysUserDao.selectById(id);
        if(sysUser==null)
            throw new ServiceException("此用户可能已经不存在");
        List<Integer> roleIds = sysUserRoleDao.selectRoleIdsByUserId(id);
        sysUser.setRoleIds(roleIds);
        return sysUser;
    }

    @Override
    public int saveUser(SysUser sysUser) {
        String password = sysUser.getPassword();
        String salt = UUID.randomUUID().toString();
        SimpleHash sh = new SimpleHash("MD5", password, salt, 1);
        String hashedPassword = sh.toHex();
        sysUser.setSalt(salt);
        sysUser.setPassword(hashedPassword);
        int rows = sysUserDao.insertUser(sysUser);
        sysUserRoleDao.insertUserRoles(sysUser.getId(), sysUser.getRoleIds());
        return rows;
    }

    @Override
    public int updateUser(SysUser sysUser) {
        int rows = sysUserDao.updateUser(sysUser);
        if(rows==0)
            throw new ServiceException("记录可能已经不存在了");
        sysUserRoleDao.deleteByUserId(sysUser.getId());
        sysUserRoleDao.insertUserRoles(sysUser.getId(), sysUser.getRoleIds());
        return rows;
    }

    @RequiresPermissions("sys:user:update")
    @Override
    public int validById(Integer id, Integer valid,String modifiedUser) {
        int rows = sysUserDao.validById(id, valid, modifiedUser);
        if(rows==0)
            throw new ServiceException("记录可能已经不存在了");
        return rows;
    }
}
